<script setup>
import TextEitdor from'@/views/text/TextEitdor.vue';
import { selectAllDep} from '@/api/department';
import { selectAnctBy,updateAnctBy,selectAnctOne } from '@/api/announcemt';
import { ref,onMounted} from 'vue';
import { useUserStore } from '@/stores/user';
const userstore=useUserStore()
const user=userstore.user
// import { ElMessage, ElDialog, ElForm, ElFormItem, ElInput, ElButton } from 'element-plus';
const dialogVisible = ref(false); // 控制弹窗显示/隐藏
const form = ref({}); // 表单数据

const rules = {
    title: [
      { required: true, message: '请输入公告标题', trigger: 'blur' },
    ],
    introduction: [
      { required: true, message: '请输入公告简介', trigger: 'blur' },
      { max: 20, message: '公告简介不能超过20个字', trigger: 'blur' }
    ],
    effectiveDate: [
      { required: true, message: '请选择生效日期', trigger: 'blur' },
    ],
    main: [
      { required: true, message: '请输入公告内容', trigger: 'blur' },
    ],
  };// 表单验证规则

const formRef = ref(null); // 表单引用
const openDialog=(async(id)=>{
    dialogVisible.value = true;
    const response= await selectAnctOne(id);
    form.value= response.data.data
})

const handleClose = () => {
  dialogVisible.value = false;
  formRef.value.resetFields(); // 清空表单
};

const handleSubmit = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      // 提交逻辑
      // 获取当前日期
const today = new Date();

// 获取年、月、日
const year = today.getFullYear();
const month = today.getMonth() + 1; // 月份从0开始，需要加1
const date = today.getDate();

// 格式化为 YYYY-MM-DD 的形式
const formattedDate = `${year}-${month.toString().padStart(2, '0')}-${date.toString().padStart(2, '0')}`;
      form.value.publishDate=formattedDate
      updateAnctBy(form.value)
      ElMessage({
        type: 'success',
        message: '修改成功',
      });
      dialogVisible.value = false;
      setTimeout(select,1000)
    } else {
      ElMessage({
        type: 'error',
        message: '请填写完整信息',
      });
      return false;
    }
  });
};
const tableData=ref([])
const title=ref('')
const state=ref('')
const publishUnit=ref('')
const publishUnitList=ref([])
const announcement=(async(data,num,text)=>{
    ElMessageBox.confirm(
    '确定要'+text+'该项目吗',
    text,
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      const mydata=data
      mydata.approval=num
      if(updateAnctBy(mydata))
        ElMessage({
        type: 'success',
        message: '申报成功！',
        })
        setTimeout(select,1000)
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '已取消申报',
      })
    })
})
const select=(async()=>{
    let response={}
    response= user.departmentId? await selectAnctBy(title.value,state.value,publishUnit.value,user.departmentId,false):await selectAnctBy(title.value,state.value,publishUnit.value,0,false);
    tableData.value= response.data.data
})
onMounted(async ()=>{
    const response = await selectAllDep();
    publishUnitList.value = response.data.data;
    select()
    // 页面加载时获取当前路径
})
const reset=()=>{
    title.value='';
    state.value='';
    publishUnit.value='';
}
</script>

<template>
    <div>
        <el-row :gutter="10" style="margin-bottom: 10px;">
            <el-col :span="5" :offset="3">
                <el-input v-model="title" clearable>
                    <template #prefix>
                        标题：
                    </template>
                </el-input>
            </el-col>
            <el-col :span="5">
                <el-select v-model="state" placeholder="请选择" style="">
                    <template #prefix>
                        状态：
                    </template>
                    <el-option label="未申报" value="1" />
                    <el-option label="待审批" value="2" />
                    <el-option label="已通过" value="3" />
                    <el-option label="已发布" value="4" />
                </el-select>
            </el-col>
            <el-col v-if="user.departmentId==null" :span="5">
                <el-select v-model="publishUnit" placeholder="请选择" style="">
                    <template #prefix>
                        发布单位：
                    </template>
                    <el-option v-for="publish_unit,index in publishUnitList":key="index" :label="publish_unit.departmentName" :value="publish_unit.departmentId" />
                </el-select>
            </el-col>
            <el-col :span="4" :offset="1">
                <el-button type="primary" @click="reset">重置</el-button>
                <el-button @click="select">
                    查询
                </el-button>
            </el-col>
        </el-row>
        <el-table :data="tableData" border style=" width:100%">
            <el-table-column prop="title" label="标题" />
            <el-table-column prop="publishDate" label="发布时间" />
            <el-table-column prop="publishUnitName" label="发布单位" />
            <el-table-column prop="publisherName" label="发布人" />
            <el-table-column prop="state" label="状态" width="120"/>
            <el-table-column label="批注" width="100">
                <template #default="scope">
                    <el-popover
                        v-if="scope.row.comments!=null"
                        placement="top-start"
                        title="批注"
                        :width="200"
                        trigger="click"
                        :content="scope.row.comments">
                        <template #reference>
                            <el-button class="m-2">查看</el-button>
                        </template>
                    </el-popover>
                    <p v-else></p>
                </template>
            </el-table-column>
            <el-table-column fixed="right" label="操作" width="200">
                <template #default="scope">
                    <el-button v-if="scope.row?.approval == 1||scope.row.approval == 5"   type="primary" size="small" @click="announcement(scope.row,2,'申报')">
                        申报
                    </el-button>
                    <el-button v-if="scope.row.approval == 1||scope.row.approval == 5"  type="primary" size="small" @click="openDialog(scope.row.id)">
                        编辑
                    </el-button>
                    <el-button v-if="scope.row?.approval == 3"  type="primary" size="small" @click="announcement(scope.row,4,'发布')">
                        发布
                    </el-button>                
                </template>
            </el-table-column>
        </el-table>
        <!-- 自定义表单弹窗 -->
        <el-dialog
        v-model="dialogVisible"
        title="编辑公告"
        width="50%"
        @close="handleClose"
        >
            <el-form
                ref="formRef"
                :model="form"
                :rules="rules"
                label-width="80px"
            >
                <el-form-item label="公告标题" prop="title">
                    <el-input v-model="form.title" />
                </el-form-item>
                <el-form-item label="公告简介" prop="introduction">
                    <el-input v-model="form.introduction" />
                </el-form-item>
                <el-form-item label="生效时间" prop="effectiveDate">
                    <el-date-picker
                    v-model="form.effectiveDate"
                    type="date"
                    aria-label="请选择日期"
                    placeholder="请选择日期"
                    style="width: 100%"
                    value-format="YYYY-MM-DD"/>
                </el-form-item>
                <el-form-item label="内容" prop="main">
                    <TextEitdor v-model="form.main"/>
                </el-form-item>
            </el-form>

            <template #footer>
                <el-button @click="handleClose">取消</el-button>
                <el-button type="primary" @click="handleSubmit">保存</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<style lang="scss" scoped>
    
</style>